import eventBus from '../core/EventDispatcher';
import {VCairnEvent} from "./VCairnEvent";
import {BaseCommandConstructor} from "../base/BaseCommand";

export class VCairnConnector {
    protected commands = new Map<string, BaseCommandConstructor|null>();

    constructor() {
        this.executeCommand = this.executeCommand.bind(this);
        this.removeCommand = this.removeCommand.bind(this);
    }

    addCommand(commandName:string, Clazz:BaseCommandConstructor) {
        if (this.commands.get(commandName)) {
            throw new Error(`${commandName}已存在`);
        }
        this.commands.set(commandName, Clazz);
        eventBus.on(commandName, this.executeCommand);
    }

    executeCommand(evt:VCairnEvent) {
        const Cmd = this.commands.get(evt.type);
        if (!Cmd) {
            throw new Error(`找不到 ${evt.type}`);
        }
        new Cmd().execute(evt);
    }

    removeCommand(commandName:string) {
        const Cmd = this.commands.get(commandName);
        if (Cmd) {
            this.commands.set(commandName, null);
            this.commands.delete(commandName);
            eventBus.off(commandName, this.executeCommand);
        }
    }
}